const formatTime = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  );
};

const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

const query = obj => {
  const queryObj = {};
  const search = obj.split('?');
  console.log(obj);

  if (search.length) {
    return {};
  }

  const querys = search[1].split('&');

  querys.forEach(queryItem => {
    const item = queryItem.split('=');

    item.forEach(oItem => {
      queryObj[oItem[0]] = oItem[1];
    });
  });

  return queryObj;
};

const navigate = function(e) {
  const {
    currentTarget: {
      dataset: { path },
    },
  } = e;
  const url = path ? `${path}/${path}` : 'home/home';

  console.log(e, url);

  wx.navigateTo({
    url: `/pages/${url}`,
  });
};

const validInfo = {
  mobile: /1[3|5|7|8|9]{9}/,
};

const navigateBackMiniProgram = appId => {
  wx.navigateToMiniProgram({
    appId: appId || 'wxe4de340f7e20fa7d',
    success: res => {},
    fail: err => {
      wx.showToast({
        title: '跳转店促通失败',
        icon: 'none',
      });
      wx.navigateTo({
        url: '/pages/index/index',
      })
      console.log(err, '跳转店促通失败');
    },
  });
};

module.exports = {
  formatTime,
  query,
  navigate,
  validInfo,
  navigateBackMiniProgram,
};
